package org.zjx.service.impl;


import org.zjx.db.ItemInstanceDB;
import org.zjx.db.ItemSlotDB;
import org.zjx.db.ItemTemplateDB;
import org.zjx.enums.prop.SlotType;
import org.zjx.matcher.TemplateMatcher;
import org.zjx.model.prop.ItemInstance;
import org.zjx.model.prop.ItemSlot;
import org.zjx.model.prop.ItemTemplate;
import org.zjx.model.prop.SlotItem;
import org.zjx.repository.ItemInstanceRepository;
import org.zjx.repository.ItemSlotRepository;
import org.zjx.repository.ItemTemplateRepository;
import org.zjx.repository.impl.ItemInstanceRepositoryImpl;
import org.zjx.repository.impl.ItemSlotRepositoryImpl;
import org.zjx.repository.impl.ItemTemplateRepositoryImpl;
import org.zjx.service.ItemManager;
import org.zjx.service.ItemStackService;
import org.zjx.service.ItemValidator;
import org.zjx.service.PropService;
import org.zjx.util.ImageUtil;

import java.awt.image.BufferedImage;
import java.util.*;
import java.util.stream.Collectors;


public class PropServiceImpl implements PropService {
    public static ItemManager itemManager;
    public static TemplateMatcher templateMatcher;

     static {

        // 创建表
        ItemTemplateDB templateDB = new ItemTemplateDB();
        ItemSlotDB slotDB = new ItemSlotDB();
        ItemInstanceDB instanceDB = new ItemInstanceDB();

        ItemInstanceRepository instanceRepo = new ItemInstanceRepositoryImpl(instanceDB);
        ItemSlotRepository slotRepo = new ItemSlotRepositoryImpl(slotDB);
        ItemTemplateRepository templateRepo = new ItemTemplateRepositoryImpl(templateDB);

        ItemStackService stackService = new ItemStackService(templateRepo);
        ItemValidator validator = new ItemValidator(slotRepo, templateRepo);

        itemManager = new ItemManagerImpl(instanceRepo, slotRepo, templateRepo, stackService, validator);
         templateMatcher = new TemplateMatcher(templateDB);
    }


    @Override
    public Optional<ItemTemplate> matcher(BufferedImage image) {
        return templateMatcher.match(image);
    }

    @Override
    public List<ItemTemplate> matcher(List<String> bufferedImages) {
         if (bufferedImages == null || bufferedImages.isEmpty()) return Collections.emptyList();
         List<BufferedImage> images = new ArrayList<>();
         for (String bufferedImage : bufferedImages) {
             images.add(ImageUtil.stringToBufferedImage(bufferedImage));
         }
        return templateMatcher.matchBatch(images);
    }

    @Override
    public List<ItemSlot> findItem(String playerId, int itemTemplateId, Map<String, Object> attributes) {
        return itemManager.findItem(playerId,itemTemplateId,attributes);
    }

    @Override
    public List<ItemInstance> getPlayerItemsBySlotType(String playerId, SlotType slotType) {
        return itemManager.getPlayerItemsBySlotType(playerId,slotType);
    }

    @Override
    public Boolean haveInstances(String playerId, int itemTemplateId, Map<String, Object> attributes) {
        return !findItem(playerId,itemTemplateId,attributes).isEmpty();
    }

    @Override
    public List<ItemInstance> needGather(String playerId, SlotType slotType) {
        return itemManager.needGather(playerId,slotType);
    }

    @Override
    public Boolean handOff(String playerId, SlotType slotType1, SlotType SlotType2) {
        return itemManager.handOff(playerId,slotType1,SlotType2);
    }

    @Override
    public Boolean moveItem(String playerId, int instanceId, int targetSlotId) {
        return itemManager.moveItem(playerId,instanceId,targetSlotId);
    }

    @Override
    public Boolean updateItem(String playerId, ItemInstance instance) {
         if (instance == null) return false;
        return itemManager.updateItem(playerId,instance);
    }

    @Override
    public Boolean updateItems(String playerId, List<ItemInstance> instances) {
         if (instances == null || instances.isEmpty()) return false;
        return itemManager.updateItems(playerId,instances);
    }

    @Override
    public List<ItemInstance> syncSlotItems(String playerId, List<SlotItem> slotItems, SlotType slotType) {
        return itemManager.syncSlotItems(playerId,slotItems,slotType);
    }

    @Override
    public List<ItemSlot> getItemSlots(String playerId, List<ItemInstance> instances) {
        // 1. 检查输入参数是否有效
        if (playerId == null || playerId.isEmpty() || instances == null || instances.isEmpty()) {
            return Collections.emptyList();
        }

        // 2. 从实例中提取所有唯一的slotId
        List<Integer> slotIds = instances.stream()
                .map(ItemInstance::getSlotId)
                .distinct()
                .collect(Collectors.toList());

        // 3. 如果没有任何slotId，返回空列表
        if (slotIds.isEmpty()) {
            return Collections.emptyList();
        }

        // 4. 查询数据库获取对应的ItemSlot
        return slotIds.stream()
                .map(slotId -> {
                    // 使用ItemSlotRepository查询slot信息
                    Optional<ItemSlot> slot = itemManager.getItemSlotRepository().findById(slotId);
                    // 确保slot属于当前玩家（可选的安全检查）
                    // 这里可以添加额外的验证逻辑，比如验证slot是否属于该玩家
                    return slot.orElse(null);
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    @Override
    public ItemTemplate getItemTemplate(int itemTemplateId) {
        return new ItemTemplateDB().findById(itemTemplateId);
    }

    @Override
    public ItemTemplate getItemTemplateByName(String itemTemplateName) {
        return new ItemTemplateDB().findByName(itemTemplateName);
    }
}
